package org.jeecgframework.tag.core.util;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;

import org.jeecgframework.tag.core.base.TagEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkUtil {

    private static final Logger         logger = LoggerFactory.getLogger(FreemarkUtil.class);
    /**
     * 配置实例
     */
    private static Configuration        cfg;

    private static Map<String, String>  tagNameMap;
    /**
     * 模板加载器,因为要处理一些无用的字符,所以这里使用String 自己加载文件
     */
    private static StringTemplateLoader templateLoader;

    static {
        templateLoader = new StringTemplateLoader();
        cfg = new Configuration();
        cfg.setTemplateLoader(templateLoader);
        cfg.setLocale(Locale.CHINA);
        cfg.setDefaultEncoding("UTF-8");
        initAllFlt();
        initProperties();
    }

    public static Template getTemplate(TagEnum name) {
        try {
            return cfg.getTemplate(name.getValue());
        } catch (IOException e) {
            logger.error(e.getMessage(), e.fillInStackTrace());
            throw new RuntimeException("没有找到模板");
        }
    }

    private static void initProperties() {
        tagNameMap = new PropertiesUtil().getProperties();
    }

    /**
     * 初始化所以FLT文件
     */
    private static void initAllFlt() {
        logger.info("start to load jeecgframework tag flt");
        FileUtil fileUtil = new FileUtil();
        for (TagEnum tag : TagEnum.values()) {
            String content = fileUtil.getFileConten("org/jeecgframework/tag/core/flt/"
                                                    + tag.getValue() + ".flt");
            content = getFltText(content);
            templateLoader.putTemplate(tag.getValue(), content);
        }
    }

    /**
     * 除去无效字段
     */
    private static String getFltText(String text) {
        if (logger.isDebugEnabled()) {
            return text;
        }
        return text.replaceAll("\\n", " ").replaceAll("\\t", " ").replaceAll("\\s{1,}", " ").trim();
    }

    public static Map<String, String> getTagNameMap() {
        return tagNameMap;
    }

}
